package com.system.shiro.realm;  
import java.util.List;  
import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;  
import org.apache.shiro.authc.AuthenticationInfo;  
import org.apache.shiro.authc.AuthenticationToken;  
import org.apache.shiro.authc.SimpleAuthenticationInfo;  
import org.apache.shiro.authc.UsernamePasswordToken;  
import org.apache.shiro.authz.AuthorizationInfo;  
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.InvalidSessionException;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.util.StringUtils;

import com.system.common.util.SessionUtil;
import com.system.permission.dao.PermissionRepository;
import com.system.permission.entity.Permission;
import com.system.role.dao.RoleRepository;
import com.system.role.entity.Role;
import com.system.user.dao.UserRepository;
import com.system.user.entity.User;

public class CustomRealm extends AuthorizingRealm{    
    @Resource  
    private UserRepository userRepository;  
    @Resource  
    private PermissionRepository permissionRepository;  
    @Resource  
    private RoleRepository roleRepository;  
      
    /** 
     * 添加角色 
     * @param username 
     * @param info 
     */  
    private void addRole(String username, SimpleAuthorizationInfo info) {  
    	User user = userRepository.findUserByUserName(username);
    	Role role = user.getRole();
        if(role!=null) {
              info.addRole(role.getRoleName());  
        }  
    }  
  
    /** 
     * 添加权限 
     * @param username 
     * @param info 
     * @return 
     */  
    private SimpleAuthorizationInfo addPermission(String username,SimpleAuthorizationInfo info) { 
    	User user = userRepository.findUserByUserName(username);
    	Role role = user.getRole();
    	List<Permission> permissions = role.getPermissionLists();  
        for (Permission permission : permissions) {  
            info.addStringPermission(permission.getUrl());//添加权限    
        }  
        return info;    
    }    
       
    /** 
     * 获取授权信息 
     */  
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {    
        //用户名    
        String username = (String)super.getAvailablePrincipal(principals);  
        //根据用户名来添加相应的权限和角色  
        if(!StringUtils.isEmpty(username)){  
            SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();  
            addPermission(username,info);  
            addRole(username, info);  
            return info;  
        }  
        return null;    
    }  
  
     
   /**  
    * 登录验证  
    */    
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken ) throws AuthenticationException {    
        //令牌——基于用户名和密码的令牌    
        UsernamePasswordToken token = (UsernamePasswordToken) authcToken;    
        
        //令牌中可以取出用户名
        String accountName = token.getUsername();  
        
        
        //让shiro框架去验证账号密码  
        System.out.println("accountName："+accountName);//输入的用户名
        if(!StringUtils.isEmpty(accountName)){  
            User user = userRepository.findOne(accountName);             
            System.out.println("user："+user);
            if(user != null){ 
            Role role = user.getRole();
            if(role!=null) {
            List<Permission> permissions = role.getPermissionLists();
        	this.setSession("permissions",permissions);
            System.out.println("permissions："+permissions);}
            System.out.println("set-userId："+user.getUid());
            
    		this.setSession("userId",user.getUid());
    		
    		System.out.println();
    		
        	this.setSession("deletes",true);
        
        	this.setSession("msg", "密码错误"); 
            return new SimpleAuthenticationInfo(user.getUid(), user.getPassword(), getName());  
            }else{  
            	this.setSession("msg", "用户不存在"); 
                throw new AuthenticationException();
            }   
        }  
          
        return null;  
    }    
    private void setSession(Object key, Object value){  
        Session session = getSession();  
        System.out.println("Session默认超时时间为[" + session.getTimeout() + "]毫秒");  
        if(null != session){  
            session.setAttribute(key, value);  
        }  
    } 
    private Session getSession(){  
        try{  
            Subject subject = SecurityUtils.getSubject();
            Session session = subject.getSession(false);  
            if (session == null){  
                session = subject.getSession();  
            }  
            if (session != null){  
                return session;  
            }  
        }catch (InvalidSessionException e){  
              
        }  
        return null;  
    }  
}    